package cn.aiseminar.aisinterphone;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class BackgroundAcceptService extends Service {
	private BluetoothPhoneService mBTService = null;
	private PendingIntent mPendingIntent = null;
	public static final String EXTRA_PENDING_INTENT = "PENDING_INTENT";
	@SuppressLint("HandlerLeak")
	private final Handler mMessageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what)
			{
			case BluetoothPhoneService.MSG_REMOTE_DEVICE_CONNECTED:
				startVoiceActivity();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mPendingIntent = (PendingIntent)intent.getParcelableExtra(EXTRA_PENDING_INTENT); 
		
		mBTService = BluetoothPhoneService.getBluetoothPhoneService();
		mBTService.setMsgHandler(mMessageHandler);
		mBTService.startAcceptServer();
		
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void startVoiceActivity()
	{
		try {
			mPendingIntent.send();
		} catch (CanceledException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.stopSelf();
	}
}
